package com.supermap.dataservice.cloud.cust.user;

import com.alibaba.dubbo.config.annotation.Service;
import com.supermap.dataservice.cloud.cust.menu.SysMenuMapper;
import com.supermap.dataservice.cloud.cust.menu.SysMenuServiceImpl;
import com.supermap.dataservice.cloud.cust.role.SysAreaRoleMapper;
import com.supermap.dataservice.mysql.config.DynamicDataSourceContextHolder;
import com.supermap.dataservice.util.JSONUtil;
import com.supermap.dubbo.api.cloud.cust.role.TreeNodeList;
import com.supermap.dubbo.api.cloud.cust.user.SysUserService;
import org.apache.logging.log4j.util.Strings;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author aqua
 * @desc
 * @date 2019年03月04 15:14
 * @email 1301584033@qq.com
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysAreaRoleMapper sysAreaRoleMapper;
    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    public JSONUtil getUserMenu(String userId) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        return null;
    }

    //获取区域角色下面的用户
    @Override
    public JSONUtil getUserTreeAreaRole(String areaCode, Integer areaRoleId,String loginName,Integer limit) {
        if(!( Strings.isBlank(areaCode)  && areaCode.equals("null") &&
                        Strings.isBlank(loginName)  && loginName.equals("null") &&
                areaRoleId != null && areaRoleId != 0 &&
                limit != null && limit != 0 ))
        {
          return  new JSONUtil().setMsg("获取区域角色下面的用户【getUserTreeAreaRole】： 参数错误，请确认参数！");
        }

        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        return new JSONUtil().setData(sysUserMapper.getUserTreeAreaRole(areaCode,areaRoleId,loginName,limit));
    }

    @Override
    public JSONUtil putUserMenu(Integer userId,String menuIds) {
        DynamicDataSourceContextHolder.setDataSourceKey("ds2");
        List<Integer> list=new ArrayList<>();
        //删除用户菜单
        sysUserMapper.delUserMenu(userId);
        //查询用户定制的和现有的进行分配
        Set<Integer> set=new HashSet<Integer>();
        for (String str:menuIds.split(",")){
            set.add(Integer.valueOf(str));
        }
        //查询定制的
        list=sysUserMapper.getSysMenuId(userId);
        String str="";
        for(Integer integer:list){
            str+=integer+",";
        }
        //进行反推
        str=sysUserMapper.getParntysMenuId(str.substring(0,str.length()-1));
        for(String a:str.split(",")){
            set.add(Integer.valueOf(a));
        }
        list=new ArrayList<>();
        list.addAll(set);
        sysUserMapper.putMenuI(list,userId);
        return new JSONUtil();
    }





}
